import os
import json

import upyun

yun = upyun.UpYun('xxxs', username='xxx', password='xxxx')

local_top = '.'
# top_dir = '/music'
allow_extension = '.krc'


file_path_mapper = []


def work_with_dir(current_dir):
    items = list_files(current_dir)
    for item in items:
        # print item['name'], item['type'], item['size'], item['time']
        if r'N'.upper() == item['type'].upper():
            # it is file
            # print current_dir+r'/'+item['name']
            get_file(current_dir+r'/'+item['name'])
        elif r'F'.upper() == item['type'].upper():
            work_with_dir(current_dir+r'/'+item['name'])


def list_files(current_path):
    return yun.getlist(current_path)


def get_file(file_path):
    if file_path is None:
        return

    if not file_filter(file_path):
        return

    local_path = local_top+file_path
    local_path = local_path.replace(r'/', '__')
    file_path_mapper.append(local_path)
    with open(local_path, 'wb') as f:
        yun.get(file_path, f)


def file_filter(filename):
    if filename is None:
        return False

    file_parts = filename.rsplit(r'.', 1)
    try:
        return allow_extension.__contains__(file_parts[1])
    except :
        return False

# http://buertings.b0.upaiyun.com/music/playlist_080/songs/003.krc
work_with_dir(r'/music')
# print file_path_mapper
with open('./path_mapper.txt', 'wb') as mapper:
    json.dump(file_path_mapper, mapper)
